﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using LimitatorInterfaces;
using LimitatorInterfaces.UnloadServices;

namespace UnloadServices
{
    public class MicexFileUnloadProvider : IUnloadProvider
    {
        private List<string> _limits = new List<string>();

        public void AddLimit(object lim)
        {
            var limStr = lim as string;
            if (string.IsNullOrWhiteSpace(limStr))
                return;

            _limits.Add(limStr);
        }

        public void AddLimits(IEnumerable<object> limits)
        {
            throw new NotImplementedException();
        }

        public void UnloadLimits(object param)
        {
            var providerParam = param as KeyValuePair<string, string>[];

            bool wrongParam = providerParam == null || providerParam.Length == 0;

            KeyValuePair<string, string> filePath = new KeyValuePair<string, string>();

            if (!wrongParam)
            {
                filePath = providerParam.SingleOrDefault(p => p.Key == MicexFileUnloader.Res.UnloadProviderParam);
                wrongParam = string.IsNullOrWhiteSpace(filePath.Key) || string.IsNullOrWhiteSpace(filePath.Value);
            }

            if (wrongParam)
                throw new ArgumentException("Не задан путь сохранения файла лимитов", "param");

            if (_limits.Count == 0)
                throw new UnloadLimitsException("Не задана таблица лимитов для выгрузки");

            File.WriteAllLines(filePath.Value, _limits);
        }
    }
}
